import { FullEntityColumns } from '@/config/column';
import GenerateThingTable from '@/executor/tools/generate/thingTable';
import { schema } from '@/ts/base';
import orgCtrl from '@/ts/controller';
import { IForm, ITarget, TargetType } from '@/ts/core';
import { Form } from '@/ts/core/thing/standard/form';
import { exportToExcel } from '@/utils/export';
import _ from 'lodash';
import React, { useEffect, useState } from 'react';

/**
 * 订单视图
 * @returns
 */
const OrderView: React.FC<{
  form?: IForm;
  thingData: schema.XOrder;
}> = (props) => {
  // 如果没有商品信息，显示提示
  if (!props.thingData?.itemList) {
    return <p>暂无商品信息</p>;
  }
  const [resultFields, setResultFields] = useState([]);
  const [itemList, setItemList] = useState<object[]>([]);
  useEffect(() => {
    if (Array.isArray(props.thingData.itemList)) {
      const arr = props.thingData.itemList
        .filter((item) => item.resource)
        .map((item) => {
          return {
            ...JSON.parse(item.resource),
            pendingCount: item.pendingCount,
          };
        });

      setItemList(arr);
    }
  }, [props.thingData.itemList]);

  // 加载目标数据
  const loadTargetData = async (mallId: string, target: ITarget) => {
    try {
      const mallTemplate = await target.resource.templateColl.find([mallId]);

      if (Array.isArray(mallTemplate) && mallTemplate.length > 0) {
        const mallConfig = mallTemplate[0];
        return mallConfig.params; // 返回表单和热门商品配置
      }
      return {};
    } catch (error) {
      console.error('加载商城模板失败', error);
      return {};
    }
  };

  // 加载表单字段
  const loadFormFields = async (formId: string, target: ITarget) => {
    try {
      const formInfo = await target.resource.formColl.find([formId]);
      if (Array.isArray(formInfo) && formInfo.length > 0) {
        const newForm = new Form(formInfo[0], target.directory);
        return newForm.loadFields();
      }
      return [];
    } catch (error) {
      console.error('加载表单字段失败', error);
      return [];
    }
  };
  useEffect(() => {
    const fetchData = async () => {
      const targets = orgCtrl.targets.filter((item: any) =>
        [TargetType.Group, TargetType.Department, TargetType.Company].includes(
          item.typeName,
        ),
      );
      // 1. 找到对应的目标（平台或卖方）
      const target = targets.find((item) => item.metadata.id === props.thingData.groupId);
      if (!target) return; // 如果没有找到目标，直接返回
      let resultFields: any = [];

      const mallId = props.thingData.mallId;
      if (mallId) {
        const { form, hot } = await loadTargetData(mallId, target);
        // 3. 如果有常规商品表单，加载表单字段
        if (form?.id) {
          const ordinaryFormFields = await loadFormFields(form.id, target);
          resultFields = [...resultFields, ...ordinaryFormFields];
        }

        // 4. 如果有热门商品表单，加载表单字段
        if (hot?.id) {
          const hotFormFields = await loadFormFields(hot.id, target);
          resultFields = [...resultFields, ...hotFormFields];
        }
      }
      // 5. 处理字段数据，去重，并筛选掉'id'字段
      resultFields = FullEntityColumns(resultFields);
      resultFields = resultFields.filter((item: any) => item.id !== 'id');
      resultFields = _.uniqBy(resultFields, 'id');
      setResultFields(resultFields); // 更新字段数据
    };

    fetchData();
  }, [props.thingData, props.form]);

  return (
    <GenerateThingTable
      height={'50vh'}
      fields={resultFields}
      dataSource={itemList}
      remoteOperations={true}
      onExporting={(e) =>
        exportToExcel(
          e,
          props.form
            ? props.form
            : {
                name: props.thingData.remark,
                attributes:resultFields
              },
        )
      }
    />
  );
};

export default OrderView;
